/**
 * Created by yihua on 2017/2/12.
 */
var uploadFlag = true;
var goodsUrl = new Set(),
    thumbUrl = new Set(),
    imgUrl = new Set();
var specContent = [];
$(document).ready(function () {
    addCategory();
    initUploadAvatar('goods_desc_file');
    initUploadAvatar('goods_thumb_file');
    initUploadAvatar('goods_img_file');
    $("#spec_confirm").unbind('click').click(function () {
        addspec();
    });

    $("#confirm").unbind('click').click(function () {
        console.log(goodsUrl);
        console.log(thumbUrl);
        console.log(imgUrl);
        addgoods();
    });


});
function addCategory() {
    $.ajax({
        url: '/home/shop/getallcategory',
        timeout: 100000,
        type: 'get',
        dataType: 'json',
        data: {},
        success: function (rs) {
            console.log(rs)
            if (rs.errno != 0) {
                toastr.error(rs.errno);
                return false;
            } else {
                $("#cat_id").select2({
                    data: rs.data
                })
            }
        },
        error: function () {
            toastr.error('系统错误');
        }
    });
}
function addspec() {
    var flag = true;
    $("#spec_form").find("input[type='text']").each(function () {
        if ($(this).val() == "") {
            flag = false;
            return false;
        }
    })
    if (false === flag) {
        toastr.error('请输入全部信息', '', {positionClass: 'toast-bottom-center'});
        return false;
    }
    var divContent = '' +
        '<div class="form-group ms-col-input">' +
        '<label class="col-sm-1 control-label " for="spec_name">规格名称</label>' +
        '<div class="col-sm-3">' +
        '<input value=' + $("#spec_name").val() + ' class="form-control" type="text" disabled/>' +
        '</div>' +
        '<label class="col-sm-1 control-label" for="goods_number">规格数量</label>' +
        '<div class="col-sm-3">' +
        '<input value=' + $("#spec_goods_number").val() + ' class="form-control" name="spec_number" type="text" disabled/>' +
        '</div>' +
        '<label class="col-sm-1 control-label" for="spec_price">价格</label>' +
        '<div class="col-sm-2">' +
        '<input value=' + $("#spec_price").val() + ' class="form-control" name="spec_price" type="text" disabled/>' +
        '</div>' + '<span class="glyphicon glyphicon-remove delspec" style="color:red"></span>' +
        '</div>';
    $("#spec_content").append(divContent);
    $('#addspec').modal('hide');
    //$('#spec_content').append(divContent);
    $('#spec_form input').val('')
    $('.delspec').click(function () {
        $(this).parent().remove();
    });

}

function addgoods() {
    var options = {
        url: '/home/shop/addgoods',
        beforeSubmit: validate,  // pre-submit callback
        success: showResponse,  // post-submit callback
        dataType: 'json',
        type: 'post',
        /*
         data: {
         //'specs': '[{"spec_name":"color","spec_price":99.99,"spec_goods_number":33},{"spec_name":"size","spec_price":"67","spec_goods_number":30}]',
         'specs': JSON.stringify(specContent),

         },      //额外附加的参数
         */
    };
    $("#goodsform").ajaxSubmit(options)
    // bind form using 'ajaxForm'
    //$('#myFormId').ajaxForm(options);
    /*
     var btn = $("#confirm");
     btn.click(function(){
     $("#addbannerimg").ajaxSubmit(options)
     });
     */
}
function validate(formData, jqForm, options) {
    for (var i = 0; i < formData.length; i++) {
        //console.log(formData[i].name)
        if (formData[i].name == 'file' || formData[i].name == 'specs') {
            break;
        }
        if (!formData[i].value) {
            //alert('请输入所有选项 ');
            toastr.error('请输入所有选项', '', {positionClass: 'toast-bottom-center'});
            return false;
        }

    }

    $("#specs").val('')
    for (var i = 0; i < formData.length; i++) {
        if (formData[i].name == 'specs') {
            specContent = [];
            var inputList = $("#spec_content .form-group input");
            if (inputList.length) {
                for (var j = 0; j < inputList.length; j = j + 3) {
                    var specJson = {
                        'spec_name': inputList.eq(j).val(),
                        'spec_goods_number': inputList.eq(j + 1).val(),
                        'spec_price': inputList.eq(j + 2).val()
                    };
                    specContent.push(specJson);
                }
                //formData.append('specs',JSON.stringify(specContent));
                $("#specs").val(JSON.stringify(specContent));
            }
            formData[i].value = $("#specs").val()
        }
    }

    console.log(formData)
    //return false;
}


function showResponse(responseText, statusText, xhr, $form) {
    console.log(responseText);
    if (0 !== responseText.errno) {
        toastr.error(responseText.errmsg, '', {positionClass: 'toast-bottom-center'});
    } else {
        toastr.success('上传成功', '', {positionClass: 'toast-bottom-center'});
        window.location.reload();
    }
}
function initUploadAvatar(imgId) {
    var id = "#" + imgId;
    $(id).fileinput({
        uploadUrl: "/common/uploadimage", // server upload action
        showRemove: false,
        showUpload: false,
        uploadAsync: true,
        showPreview: false,
        allowedFileExtensions: ['jpg', 'png', 'gif'],
        maxFileCount: 5,
        uploadExtraData: function () {   //额外参数的关键点
            var obj = {
                'type': 1
            };
            return obj;
        }
    }).on('fileuploaded', function (event, data, id, index) {
        var ret = data.response;
        if (0 != ret.errno) {
            toastr.error('头像图片', '', {positionClass: 'toast-bottom-center'});
            uploadFlag = false;
        } else {
            var url = ret.data.url;
            if ('goods_desc_file' == imgId) {
                goodsUrl.add(url);
                $("#goods_desc").val(Array.from(goodsUrl).join('|'));

            } else if ('goods_thumb_file' == imgId) {
                console.log('add thrumbimg');
                //$("#goods_thumb").val(url);
                thumbUrl.add(url);
                $("#goods_thumb").val(Array.from(thumbUrl).join('|'));
            } else if ('goods_img_file' == imgId) {
                //$("#goods_banner").val(url);
                console.log('add goods_img_Url');
                imgUrl.add(url);
                $("#goods_img").val(Array.from(imgUrl).join('|'));
            } else {
                console.log('add nothing');
            }
        }
        console.log('upload' + imgId + 'OK ', url)
    }).on("filebatchselected", function (event, files) {
        $(id).fileinput("upload");
    });
}
